package edu.yourl.web.components;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import edu.yourl.web.GossiperPage;

@SuppressWarnings("serial")
public abstract class ActionBar extends Panel {

	public ActionBar(String id,final IModel<GossiperPage> model) {
		super(id,model);
		
		AjaxLink<?> favoriteLink = new AjaxLink<String>("favorite") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				ActionBar.this.addToFavorites(target);
			}
			
			@Override
			public boolean isEnabled() {
				return ActionBar.this.isLinkEnabled();
			}
			
			@Override
			protected void onComponentTagBody(MarkupStream markupStream,
					ComponentTag openTag) {
				super.onComponentTagBody(markupStream, openTag);
				String messageAdded = isEnabled() ? "Agregar a favoritos" : "Ya es favorito tuyo";
				replaceComponentTagBody(markupStream, openTag, messageAdded);
			}
			
			@Override
			public boolean isVisible() {
				return !model.getObject().isMyPage();
			}
		};
		
		favoriteLink.setOutputMarkupId(true);
		add(favoriteLink);
		
		WebMarkupContainer followLinkContainer = new WebMarkupContainer("followLinkContainer");
		followLinkContainer.setVisible(!model.getObject().getGossiperType().getSimpleName().equals("User"));

		ExternalLink followLink = new ExternalLink("followLink", ActionBar.this.getHyperLink(model.getObject().getFollowLink())) {
			
			@Override
			protected void onComponentTagBody(MarkupStream markupStream,
					ComponentTag openTag) {
				super.onComponentTagBody(markupStream, openTag);
				replaceComponentTagBody(markupStream, openTag, "Ir al sitio");
			}
		};
		followLinkContainer.add(followLink);
		add(followLinkContainer);
		
	}
	
	private String getHyperLink(String url) {
		if (url != null) {
			if (!url.subSequence(0, 3).equals("http")) {
				url = "http://" + url;
			}
			return url;
		}
		return null;
	}

	protected abstract void addToFavorites(AjaxRequestTarget target);
	
	protected abstract boolean isLinkEnabled();

}
